################################################################################
##### Auxiliary functions for the analysis #####
################################################################################

##### Create a customized table from fixest calls (for balance tests) #####

## Customize appearance of SEs 
custom_se <- function(x){
  x <- paste0("(", x, ")")
  x
}

## Extract statistics to report
balance_coefs <- function(fit){
  # Variable for which we check balance
  depvar <- etable(fit)["Dependent Var.:",]
  
  # Coef, SE, and p-value of the balance regression
  coef <- coefficients(fit)["strength_loy"]
  se <- se(fit)["strength_loy"]
  p <- pvalue(fit)["strength_loy"]
  
  out <- cbind(depvar, round(cbind(coef, se, p), 3))
  
  # Customize for table
  out[,"se"] <- custom_se(out[,"se"])
  out
}


##### Run regressions on trimmed samples #####
## Trim the sample from extreme top and bottom values
trim <- function(df, var, qt) {
  d <- as.data.frame(anti_join(df, bind_rows(slice_max(df, order_by = {{ var }}, prop = qt),
                                             slice_min(df, order_by = {{ var }}, prop = qt))))
  return(d)
}

## Run models on the trimmed sample and store estimates
do_trim <- function(var){
  trimmed <- matrix(,nrow=length(range), ncol=4)
  formula <- paste0(var, "~", "strength_loy + fs_loy + log_height + log_area + log_pop_70 + pnv_share_33 | prov")
  for(j in 1:length(range)){
    i <- range[j]
    fit <- feols(fml = as.formula(formula), vcov = conley_vcov, data = trim(subset(data_final, eus==1), var=strength_loy, qt=i))
    coef <- coef(fit)["strength_loy"]
    ci <- confint(fit)["strength_loy",]
    trimmed[j, 1] <- i
    trimmed[j, 2] <- coef
    trimmed[j, 3] <- as.numeric(ci[1])
    trimmed[j, 4] <- as.numeric(ci[2])
  }
  colnames(trimmed) <- c("qt", "coef", "lower", "upper")
  as.data.frame(trimmed)
}

##### Coefficient plots for the ETA analysis #####

## Plot for the attacks and victims regressions
plot_eta_coefs <- function(fitlist){
  x <- cbind(1+length(fitlist)-c(1:length(fitlist)),
             c(rep("1968-1977",2), rep("1978-1994",2), rep("1995-2003",2)),
             rep(c("Log.", "Dummy"),3),
             do.call("rbind", lapply(fitlist, function(x) coef(x)["strength_loy"])),
             do.call("rbind", lapply(fitlist, function(x) confint(x)["strength_loy",])))
  x <- as.data.frame(x)
  colnames(x) <- c("id", "period", "transformation", "coef", "ll", "ul")
  ggplot(x, aes(x=coef, y=id, shape=transformation)) + geom_point() + geom_errorbar(aes(xmin=ll, xmax=ul), color="black") +
    guides(shape = guide_legend(reverse=TRUE)) +
    geom_vline(xintercept=0, linetype="dashed", color="blue") +
    geom_hline(yintercept=c(2.5, 4.5), linetype="dotted", color="red") +
    scale_y_discrete(limits=c(1.5, 3.5, 5.5), labels=c("1995-2003", "1978-1994", "1968-1977")) +
    scale_x_continuous(limits=c(-0.75, 0.75)) + 
    labs(y="", x="") + 
    scale_shape_manual(name="", values=c(2,1)) +
    theme_bw()
}

## Plot for the prisoners regressions
plot_eta_coefs2 <- function(fitlist){
  x <- cbind(1+length(fitlist)-c(1:length(fitlist)),
             c("Log.", "Dummy"),
             do.call("rbind", lapply(fitlist, function(x) coef(x)["strength_loy"])),
             do.call("rbind", lapply(fitlist, function(x) confint(x)["strength_loy",])))
  x <- as.data.frame(x)
  colnames(x) <- c("id", "transformation", "coef", "ll", "ul")
  ggplot(x, aes(x=coef, y=id, shape=transformation)) + geom_point() + geom_errorbar(aes(xmin=ll, xmax=ul), color="black") +
    guides(shape = guide_legend(reverse=TRUE)) +
    geom_vline(xintercept=0, linetype="dashed", color="blue") +
    scale_y_discrete(limits=c(1,2)) + 
    scale_x_continuous(limits=c(-0.75, 0.75)) + 
    labs(y="", x="") + 
    scale_shape_manual(name="", values=c(2,1)) +
    theme_bw()
}